#!/usr/bin/python
# -*- coding:utf-8 -*-
# power by Mr.Li
import visdom
import time
import numpy as np
import torch
class Visualizer(object):
    '''
    封装了visdom的基本操作，但是你仍然可以通过`self.vis.function`
    调用原生的visdom接口
    '''
    def __init__(self, env='default', **kwargs):
        self.vis = visdom.Visdom(env=env, **kwargs)
        # 画的第几个数，相当于横座标
        # 保存（’loss',23） 即loss的第23个点
        self.index = {}
        self.log_text = ''
    def reinit(self,env='default',**kwargs):
        '''
        修改visdom的配置  重新初始化
        '''
        self.vis = visdom.Visdom(env=env,**kwargs)
        return self
    def plot_many(self, d):
        '''
        一次plot多个损失图形
        @params d: dict (name,value) i.e. ('loss',0.11)
        '''
        for k, v in d.items():
            self.plot(k, v)
    def img_many(self, d):
        '''
     一次画多个图像
        '''
        for k, v in d.items():
            self.img(k, v)
    def plot(self, name, y,**kwargs):
        '''
        self.plot('loss',1.00)
        '''
        #得到下标序号
        x = self.index.get(name, 0)
        self.vis.line(Y=np.array([y]), X=np.array([x]),
                      win=name,#窗口名
                      opts=dict(title=name),
                      update=None if x == 0 else 'append', #按照append的画图形
                      **kwargs
                      )
        #下标累加1
        self.index[name] = x + 1
    def img(self, name, img_,**kwargs):
        '''
        self.img('input_img',t.Tensor(64,64))
        self.img('input_imgs',t.Tensor(3,64,64))
        self.img('input_imgs',t.Tensor(100,1,64,64))
        self.img('input_imgs',t.Tensor(100,3,64,64),nrows=10)

        ！！！don‘t ~~self.img('input_imgs',t.Tensor(100,64,64),nrows=10)~~！！！
        '''
        self.vis.images(img_.cpu().numpy(),
                       win=name,
                       opts=dict(title=name),
                       **kwargs
                       )
    def log(self,info,win='log_text'):
        '''
        self.log({'loss':1,'lr':0.0001})
        打印日志
        '''

        self.log_text += ('[{time}] {info} <br>'.format(
                            time=time.strftime('%m%d_%H%M%S'),\
                            info=info))
        self.vis.text(self.log_text,win)
    def __getattr__(self, name):
        return getattr(self.vis, name)

    def create_vis_plot(self,_xlabel, _ylabel, _title, _legend):
        viz = visdom.Visdom()
        '''
        新增可视化图形
        '''
        return viz.line(
            X=torch.zeros((1,)).cpu(),
            Y=torch.zeros((1, 3)).cpu(),
            opts=dict(
                xlabel=_xlabel,
                ylabel=_ylabel,
                title=_title,
                legend=_legend
            )
        )

